import React, { ChangeEvent, useEffect, useState } from 'react'
import * as api from '../../services/api'
import Article from '../../type'
import ArticleItem from '../ArticleItem'
import { message, Pagination, ConfigProvider, Form, Input, Button } from 'antd'
import style from './style.module.less'
import zhCN from 'antd/es/locale/zh_CN'

export default function ArticleList(props: any) {
  let token: string = props.token
  let pageSizeOptions: string[] = ['5', '10', '20', '50']
  let limit: number = 10

  const [dataSource, setDataSource] = useState<Article[]>([])
  const [pageIndex, setPageIndex] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(5)
  const [total, setTotal] = useState<number>(0)
  const [keywords, setKeywords] = useState<string>('')
  const [update, setUpdate] = useState<boolean>(true)

  useEffect(() => {
    getDataSource(pageIndex, pageSize, keywords)
    getTotal()
  }, [])

  useEffect(() => {
    getDataSource(pageIndex, pageSize, keywords)
    getTotal()
  }, [update])

  async function getDataSource(pageI: number, pageS: number, keyword: string) {
    try {
      let getIf: boolean = true
      let res = await api.searchOwnerArticle(token, pageI, pageS, keyword)
      if (res.data.stat === 'ok') {
        let resData: Article[] = []
        if (resData.length > 0) resData = []
        if (res.data.data.items.length === 0) {
          getIf = false
        }
        res.data.data.items.map((data: any) => {
          let Article: Article = {
            author: data.author.account,
            banner: data.banner,
            content: data.content,
            ctime: data.ctime,
            preview: data.preview,
            subTitle: data.subTitle,
            tags: data.tags,
            title: data.title,
            id: data._id,
          }
          resData.push(Article)
          return null
        })
        if (resData.length === 0) {
          message.destroy()
          message.success('当前关键字无相关数据')
          if (getIf) {
            getDataSource(1, pageSize, '')
          }
        }
        setDataSource(resData)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  async function getTotal() {
    try {
      let res = await api.searchOwnerArticle(token, 0, 0, keywords)
      if (res.data.stat === 'ok') {
        setTotal(res.data.data.items.length)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  function showTotal(num: number) {
    return <span>共 {num} 篇文章</span>
  }

  function pageOnchange(page: number, pageSize: any) {
    setPageIndex(page)
    setPageSize(pageSize)
    getDataSource(page, pageSize, keywords)
  }

  function getDataSourceByKeywords() {
    getDataSource(pageIndex, pageSize, keywords)
    getTotal()
    setKeywords('')
  }

  function setKeywordsOnchange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setKeywords(e.target.value)
    } else {
      setKeywords(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`关键字长度不能超过${limit}个`)
    }
    if (keywords === '') {
      getDataSource(pageIndex, pageSize, keywords)
      getTotal()
    }
  }

  return (
    <>
      <div className={style.head}>
        <ConfigProvider locale={zhCN}>
          <Pagination
            className={style.Pagination}
            pageSizeOptions={pageSizeOptions}
            showSizeChanger={true}
            showQuickJumper={true}
            showTotal={(total) => showTotal(total)}
            total={total}
            pageSize={pageSize}
            current={pageIndex}
            onChange={(page, pageSize) => pageOnchange(page, pageSize)}
          />
        </ConfigProvider>
        <Form.Item className={style.form}>
          关键字：
          <Input
            value={keywords}
            onChange={(event) => setKeywordsOnchange(event)}
            className={style.formInput}
          />
          <Button
            className={style.formButton}
            onClick={getDataSourceByKeywords}
            type={'primary'}>
            搜索
          </Button>
        </Form.Item>
      </div>
      <div className={style.content}>
      {dataSource.map((data) => (
        <ArticleItem
          button={true}
          key={data.id}
          changeUpdate={(e: boolean) => setUpdate(e)}
          update={update}
          token={token}
          dataSource={data}
        />
      ))}
      </div>
    </>
  )
}
